<template>
    <div>
        <el-row class="padding-tb">
            <el-col :span="24" align="left">
                <el-input v-model="searchConditions.name" clearable size="mini" class="blue-bg" placeholder="请输入角色名称">
                    <el-button type="primary" slot="append" size="mini" style="background-color: #409EFF !important;color:#fff" @click="fetchData(1,searchConditions.pageSize)">搜索</el-button>
                    <el-button type="primary" slot="prepend" size="mini" style="background-color: #409EFF !important;color:#fff" v-if="isLogin" @click="infoCreate">添加角色</el-button>
                </el-input>
                <el-radio-group v-model="viewMode" size="mini">
                    <el-radio-button label="DKP">DKP</el-radio-button>
                    <el-radio-button label="ATTENDANCE_RATIO">出勤率</el-radio-button>
                </el-radio-group>
            </el-col>
        </el-row>
        <div class="padding-tb">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin-top:10px;"></div>
            <el-checkbox-group v-model="checkedClasses" @change="handleCheckedClassesChange">
                <el-checkbox v-for="clazz in classes" :label="clazz" :key="clazz">{{clazz}}</el-checkbox>
            </el-checkbox-group>
        </div>
        <div>
            <el-table :data="tableData.list" border stripe style="width: 100%" @sort-change="sortChange">
                <el-table-column prop="name" align="center" label="角色名" width="180">
                    <template slot-scope="scope">
                        <el-tooltip :content="`此乃【${scope.row.linkedTo}】的小号`" placement="top" effect="light" v-if="scope.row.linkedTo">
                            <el-button type="text" size="mini">{{scope.row.name}}</el-button>
                        </el-tooltip>
                        <span v-else>{{scope.row.name}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="class" align="center" label="职业" width="50">
                    <template slot-scope="scope">
                        <img class="classIcon" :src="`./static/class/${classIcons[scope.row.class]}.png`" :title="scope.row.class">
                    </template>
                </el-table-column>
                <template v-if="viewMode==='DKP'">
                    <el-table-column label="DKP" align="center" width="400">
                        <el-table-column v-for="instance of instances.slice(0,4)" :key="`${instance}-dkp`" sortable="custom" :prop="'scores.'+instance" :label="instance" width="100" align="center">
                          <template slot-scope="scope">
                            <span v-if="!scope.row.parent">{{(+scope.row.scores[instance]).toFixed(2)}}</span>
                            <el-tooltip v-else :content="`主号【${scope.row.linkedTo}】的DKP`" placement="top" effect="light">
                                <el-button type="text" size="mini">{{(+scope.row.parent.scores[instance]).toFixed(2)}}</el-button>
                            </el-tooltip>
                          </template>
                        </el-table-column>
                    </el-table-column>                    
                </template>
                <template v-else>
                    <el-table-column label="出勤率" align="center" width="500">
                        <el-table-column v-for="instance of instances" :key="`${instance}-ratio`" sortable="custom" :label="instance" width="100" align="center" :prop="`attendanceRatio.${instance}`">
                            <template slot-scope="{row}">
                                <el-tooltip v-if="!row.linkedTo" v-model="row.attendanceRatio[instance].show" effect="light" 
                                    :hide-after="0"
                                    placement="top">
                                    <div slot="content">
                                         <pie-chart v-if="row.attendanceRatio[instance].show" 
                                            :instance="instance"
                                            :classes="row.classes"
                                            :attendance-distribution="row.attendanceDistribution"
                                            :attendance-ratio="row.attendanceRatio" ></pie-chart>
                                    </div>
                                    <span class="ratio">{{row.attendanceRatio[instance].ratio}}%</span>
                                </el-tooltip>
                                <span v-else>---</span>
                            </template>
                        </el-table-column>
                    </el-table-column>                    
                </template>
                <el-table-column prop="joinTime" sortable="custom" label="首次参团日期" :formatter="dateFormatter" align="center" width="180"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="normal" size="mini" @click="viewDetail(scope)" :disabled="!!scope.row.linkedTo">DKP明细</el-button>
                        <el-button type="warning" size="mini" @click="infoModify(scope)" v-if="isLogin && level>1">修改</el-button>
                        <el-button type="primary" size="mini" @click="dkpModify(scope)" v-if="isLogin && level>1" :disabled="!!scope.row.linkedTo">DKP操作</el-button>
                        <el-button type="danger" size="mini" @click="remove(scope.row.name)" v-if="isLogin && level>1">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="padding-tb">
            <el-pagination
            @size-change="pageSizeChange"
            @current-change="pageNoChange"
            :current-page="searchConditions.pageNo"
            :page-sizes="[10, 20, 30, 50, 100]"
            :page-size="searchConditions.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.total">
            </el-pagination>
        </div>

        <el-dialog :title="`${infoForm.isCreate?'新增':'修改'}角色信息`" width="500px" :visible.sync="infoShow">
            <el-form :model="infoForm" ref="infoForm" :rules="infoRules" :label-width="formLabelWidth">
                <el-form-item label="角色名" prop="name">
                    <el-input v-model="infoForm.name" :readonly="readonly" placeholder="请输入角色名称（注意大小写）"></el-input>
                </el-form-item>
                <el-form-item label="种族" prop="race">
                    <el-select v-model="infoForm.race" placeholder="请选择种族" @change="raceChange">
                        <el-option v-for="race in races"
                            :key="race"
                            :label="race"
                            :value="race">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="职业" prop="class">
                    <el-select v-model="infoForm.class" placeholder="请选择职业">
                        <el-option v-for="clazz in allRaces[infoForm.race]"
                            :key="clazz"
                            :label="clazz"
                            :value="clazz">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="等级" prop="level">
                    <el-input-number 
                        v-model="infoForm.level" 
                        placeholder="请输入等级"
                        :min="1"
                        :max="60"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="绑定大号" prop="linkedTo">
                    <el-select v-model="infoForm.linkedTo" clearable filterable placeholder="请选择要绑定的大号">
                        <el-option v-for="player in players"
                            :key="player"
                            :label="player"
                            :value="player">
                        </el-option>
                    </el-select>
                </el-form-item>
                <template v-if="infoForm.isCreate && !infoForm.linkedTo">
                  <el-form-item v-for="(score, instance) of infoForm.scores" 
                    :label="`${instance}初始分`" prop="scores" :key="instance">
                      <el-input-number 
                          v-model="infoForm.scores[instance]" 
                          :placeholder="`请输入${instance}初始分`"
                      ></el-input-number>
                  </el-form-item>
                </template>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="infoShow = false">取 消</el-button>
                <el-button type="primary" @click="infoSubmit">保 存</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="`角色【${dkpConditions.player}】DKP变动记录`" width="1000px" :visible.sync="dkpShow">
            <el-row>
                <el-col :span="10">
                    <el-radio-group v-model="dkpConditions.type" size="mini" @change="fetchDkpData()">
                        <el-radio-button label="TAQ">TAQ</el-radio-button>
                        <el-radio-button label="NAXX">NAXX</el-radio-button>
                        <el-radio-button label="TAQ2">TAQ2</el-radio-button>
                        <el-radio-button label="NAXX2">NAXX2</el-radio-button>
                    </el-radio-group>
                    <el-radio-group v-model="dkpConditions.mode" size="mini" @change="fetchDkpData()">
                        <el-radio-button label="ALL">全部</el-radio-button>
                        <el-radio-button label="USE">扣分记录</el-radio-button>
                    </el-radio-group>
                </el-col>
                <el-col :span="12">
                    <el-date-picker
                        v-model="dkpConditions.dateRange"
                        type="datetimerange"
                        :picker-options="dkpDateOptions"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        size="mini"
                        align="right">
                    </el-date-picker>
                </el-col>
                <el-col :span="1">
                    <el-button type="primary" size="mini" @click="fetchDkpData()">搜索</el-button>
                </el-col>
            </el-row>
            <el-table :data="dkpLogs.list" border stripe 
                style="margin-top: 10px;width: 100%"
                height="500"
                >
                <el-table-column 
                    prop="time"
                    label="时间"
                    :width="160" align="center">
                </el-table-column>
                <el-table-column 
                    prop="score"
                    label="分数"
                    :width="100" align="center">
                </el-table-column>
                <el-table-column 
                    prop="reason"
                    label="原因"
                    :formatter="resonFormatter"
                    :width="140" align="center">
                </el-table-column>
                <el-table-column 
                    prop="id"
                    label="说明"
                    align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.reason=='loot'">
                            <div>
                                <span v-if="scope.row.from">关联小号【{{scope.row.from}}】</span>
                                <span v-if="scope.row.raid">在活动【{{scope.row.raid}}】中</span>获取装备
                                <span :style="{color:'#'+scope.row.color}" v-if="scope.row.itemName">【{{scope.row.itemName}}】</span>
                            </div>
                            <div v-if="scope.row.zone">活动位置：【{{scope.row.zone}}】</div>
                            <div v-if="scope.row.reasonNote">补充说明：{{scope.row.reasonNote}}</div>
                        </div>
                        <div v-else-if="scope.row.reason=='boss' || scope.row.reason=='item' && scope.row.boss">
                          <div><span v-if="scope.row.zone">在【{{scope.row.zone}}】</span><span>【<span v-html="scope.row.boss"></span>】</span></div>
                        </div>
                        <div v-else>{{scope.row.reasonNote}}</div>
                    </template>
                </el-table-column>
            </el-table>
            <div class="padding-tb">
                <el-pagination
                @current-change="dkpPageNoChange"
                :current-page="dkpConditions.pageNo"
                layout="total, prev, pager, next, jumper"
                :total=dkpLogs.total>
                </el-pagination>
            </div>
        </el-dialog>

        <el-dialog :title="`变更角色【${dkpChangeForm.player}】的DKP`" width="500px" :visible.sync="dkpChangeFormShow">
            <el-form :model="dkpChangeForm" ref="dkpChangeForm" :label-width="formLabelWidth">
                <fieldset v-for="(scoreObj, instance) of dkpChangeForm.scores" :key="instance">
                    <legend>{{instance}}</legend>
                    <el-form-item label="DKP分值">
                        <el-tooltip content="加分输入正数，减分输入负数，空或者0代表不改变" placement="top" effect="light">
                            <el-input-number 
                                v-model="scoreObj.value" 
                                placeholder="增减分数值"
                            ></el-input-number>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="增减分原因">
                        <el-select v-model="scoreObj.reason" placeholder="请选择增减分原因">
                            <el-option v-for="(reason,key) in reasons"
                                :key="key"
                                :label="reason"
                                :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="补充说明">
                        <el-input type="textarea" autosize v-model="scoreObj.reasonNote" placeholder="填写增减分的补充说明"></el-input>
                    </el-form-item>
                </fieldset>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dkpChangeFormShow = false">取 消</el-button>
                <el-button type="primary" @click="dkpChangeFormSubmit()">保 存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import PieChart from '../components/PieChart'
import {
  getPlayerList,
  getAllPlayerNames,
  playerExists,
  createPlayer,
  modifyPlayer,
  modifyDkp,
  getDkpLog,
  removePlayer
} from "../service/api";
const races = {
  兽人: ["战士", "盗贼", "术士", "猎人", "萨满祭司"],
  牛头人: ["战士", "德鲁伊", "猎人", "萨满祭司"],
  亡灵: ["战士", "盗贼", "法师", "牧师", "术士"],
  巨魔: ["战士", "盗贼", "法师", "牧师", "猎人", "萨满祭司"]
};
const classes = [
  "战士",
  "盗贼",
  "法师",
  "牧师",
  "萨满祭司",
  "术士",
  "德鲁伊",
  "猎人"
];
const classIcons = {
  "战士": "zs",
  "盗贼": "dz",
  "法师": "fs",
  "牧师": "ms",
  "萨满祭司": "sm",
  "术士": "ss",
  "德鲁伊": "dly",
  "猎人": "lr"
}
export default {
  components: {
    PieChart
  },
  data() {
    return {
      instances: ['TAQ','NAXX','TAQ2','NAXX2','TOTAL'],
      viewMode: 'DKP',
      checkAll: false,
      checkedClasses: [],
      classes,
      classIcons,
      races: Object.keys(races),
      allRaces: races,
      players: [],
      isIndeterminate: false,
      tableData: { total: 0, list: [] },
      searchConditions: {
        name: "",
        pageNo: 1,
        pageSize: 10,
        sort: "",
        order: ""
      },
      infoShow: false,
      formLabelWidth: "100px",
      infoForm: {
        isCreate: false,
        username: "",
        race: "",
        class: "",
        level: 60,
        linkedTo: null,
        scores: {
          TAQ: 0,
          NAXX: 0,
          TAQ2: 0,
          NAXX2: 0
        }
      },
      infoRules: {
        name: [
          {
            required: true,
            message: "请输入角色名称（注意大小写）",
            trigger: "blur"
          }
        ],
        race: [{ required: true, message: "请选择种族", trigger: "blur" }],
        class: [{ required: true, message: "请选择职业", trigger: "blur" }],
        level: [{ required: true, message: "请填写等级", trigger: "blur" }]
      },
      dkpShow: false,
      dkpConditions: {
        player: "",
        type: "TAQ",
        mode: "ALL",
        dateRange: [],
        pageSize: 10,
        pageNo: 1
      },
      dkpDateOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      dkpLogs: { total: 0, list: [] },
      reasons: {
        boss: "击杀boss得分",
        item: "掉落装备得分",
        collect: "集合分",
        dismiss: "解散分",
        assart: "开荒分",
        whole: "全程参与补助",
        firstDown: "Boss首次击杀",
        loot: "获取装备",
        add: "引怪导致团灭",
        ot: "OT导致团灭",
        disobey: "不听指挥",
        other: "其他"
      },
      dkpChangeFormShow: false,
      dkpChangeForm: {
        player: "",
        scores: {
          TAQ: {
            value: 0,
            reason: "other",
            reasonNote: ""
          },
          NAXX: {
            value: 0,
            reason: "other",
            reasonNote: ""
          },
          TAQ2: {
            value: 0,
            reason: "other",
            reasonNote: ""
          },
          NAXX2: {
            value: 0,
            reason: "other",
            reasonNote: ""
          }
        }
      }
    };
  },
  computed: {
    ...mapGetters(["isLogin", 'level']),
    readonly() {
      return !this.infoForm.isCreate;
    }
  },
  methods: {
    handleCheckAllChange(val) {
      this.checkedClasses = val ? classes : [];
      this.isIndeterminate = false;
    },
    handleCheckedClassesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.classes.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.classes.length;
    },
    pageSizeChange(val) {
      this.fetchData(1, val);
    },
    pageNoChange(val) {
      this.fetchData(val, this.pageSize);
    },
    viewDetail({ row }) {
      this.dkpConditions = {
        player: row.name,
        type: "TAQ",
        mode: "ALL",
        dateRange: []
      };
      this.fetchDkpData();
    },
    infoModify({ row }) {
      this.infoForm = {
        isCreate: false,
        name: row.name,
        race: row.race,
        class: row.class,
        level: row.level,
        linkedTo: row.linkedTo,
        scores: row.scores
      };
      this.infoShow = true;
    },
    infoCreate() {
      this.infoForm = {
        isCreate: true,
        name: "",
        race: "",
        class: "",
        level: "",
        linkedTo: "",
        scores: {
          TAQ: 0,
          NAXX: 0,
          TAQ2: 0,
          NAXX2: 0
        }
      };
      this.infoShow = true;
    },
    raceChange(val) {
      if (races[val].indexOf(this.infoForm.class) < 0) {
        this.infoForm.class = "";
      }
    },
    infoSubmit() {
      this.$refs["infoForm"].validate(valid => {
        if (valid) {
          if (this.infoForm.isCreate) {
            playerExists({ name: this.infoForm.name }).then(r => {
              if (r.data.data.exists) {
                this.$message({
                  showClose: true,
                  message: "该角色已经存在",
                  type: "error"
                });
              } else {
                createPlayer({
                  ...this.infoForm
                })
                  .then(_ => {
                    this.$message({
                      showClose: true,
                      message: "角色添加成功",
                      type: "success"
                    });
                    this.refreshData();
                  })
                  .finally(_ => {
                    this.infoShow = false;
                  });
              }
            });
          } else {
            modifyPlayer({
              ...this.infoForm
            })
              .then(({ data }) => {
                if (data.status == 0) {
                  this.$message({
                    showClose: true,
                    message: "角色修改成功",
                    type: "success"
                  });
                  this.refreshData();
                }
              })
              .finally(_ => {
                this.infoShow = false;
              });
          }
        }
      });
    },
    dkpModify({ row }) {
      this.dkpChangeForm.player = row.name;
      this.dkpChangeFormShow = true;
    },
    dateFormatter(row, column, cellValue, index) {
      return this.toDateString(cellValue);
    },
    toDateString(v) {
      let dt = new Date(v);
      return (
        dt.getFullYear() +
        "-" +
        ("0" + (dt.getMonth() + 1)).slice(-2) +
        "-" +
        ("0" + dt.getDate()).slice(-2) +
        " " +
        ("0" + dt.getHours()).slice(-2) +
        ":" +
        ("0" + dt.getMinutes()).slice(-2) +
        ":" +
        ("0" + dt.getSeconds()).slice(-2)
      );
    },
    sortChange({ prop, order }) {
      if(prop === 'joinTime') {
        this.searchConditions.sort = prop
      }else {
        let p = prop.split('.')
        if(p[0] === 'scores'){
            this.searchConditions.sort = p[1]
        }else{
            this.searchConditions.sort = prop
        }
      }
      this.searchConditions.order = order;
      this.refreshData();
    },
    fetchData(pageNo = 1, pageSize = 10) {
      this.searchConditions.pageNo = pageNo;
      this.searchConditions.pageSize = pageSize;
      getPlayerList({
        ...this.searchConditions,
        classes: this.checkedClasses.join(",")
      }).then(({ data }) => {
        this.tableData = data.data
      });
    },
    refreshData() {
      this.fetchData(
        this.searchConditions.pageNo,
        this.searchConditions.pageSize
      );
    },
    dkpPageNoChange(val) {
      this.fetchDkpData(val, this.dkpConditions.pageSize);
    },
    fetchDkpData(pageNo = 1, pageSize = 10) {
      this.dkpConditions.pageNo = pageNo;
      this.dkpConditions.pageSize = pageSize;
      return getDkpLog({
        ...this.dkpConditions,
        dateRange: this.dkpConditions.dateRange.map(o => this.toDateString(o))
      }).then(({ data }) => {
        this.dkpLogs = data.data;
        this.dkpShow = true;
      });
    },
    resonFormatter(row, column, cellValue, index) {
      return this.reasons[cellValue];
    },
    dkpChangeFormSubmit() {
      if (
        this.dkpChangeForm.scores.TAQ.value ||
        this.dkpChangeForm.scores.NAXX.value ||
        this.dkpChangeForm.scores.TAQ2.value ||
        this.dkpChangeForm.scores.NAXX2.value
      ) {
        if((this.dkpChangeForm.scores.TAQ.value && 
          this.dkpChangeForm.scores.TAQ.reason == 'other' &&
          !this.dkpChangeForm.scores.TAQ.reasonNote) ||
          (this.dkpChangeForm.scores.NAXX.value && 
          this.dkpChangeForm.scores.NAXX.reason == 'other' &&
          !this.dkpChangeForm.scores.NAXX.reasonNote) ||
          (this.dkpChangeForm.scores.TAQ2.value && 
          this.dkpChangeForm.scores.TAQ2.reason == 'other' &&
          !this.dkpChangeForm.scores.TAQ2.reasonNote) ||
          (this.dkpChangeForm.scores.NAXX2.value && 
          this.dkpChangeForm.scores.NAXX2.reason == 'other' &&
          !this.dkpChangeForm.scores.NAXX2.reasonNote)
          ){
          this.$alert('请输入DKP变动原因！', '提示信息');
          return;
        }

        modifyDkp({
          ...this.dkpChangeForm
        }).then(_=>{
            this.$message({
                showClose: true,
                message: "DKP变更成功",
                type: "success"
            });
            this.dkpChangeFormShow = false;
            this.refreshData();
        });
      } else {
        this.dkpChangeFormShow = false;
      }
    },
    remove(name) {
      this.$confirm(`确定要删除角色【${name}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removePlayer({name}).then(_=>{
          this.$message({
            showClose: true,
            message: "角色删除成功",
            type: "success"
          });
          this.refreshData();
        })
      }).catch(_=>{

      });
    }
  },
  created() {
    this.fetchData();
    getAllPlayerNames().then(({ data }) => {
      this.players = data.data.list;
    });
  }
};
</script>

<style lang="less" scoped>
.padding-tb {
  padding: 10px 0;
}
.blue-bg {
  width: 300px;
}
.sub-title {
  padding-bottom: 5px;
}
fieldset {
  border: 1px dashed #ddd;
  padding: 5px;
}
.classIcon{
    height: 25px;
    vertical-align: middle;
}
.ratio{
    cursor: pointer;
}
</style>
